package com.dc.ssjt.config.db;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置多数据源
 *
 * @author duchao
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean("dsStorage")
    @ConfigurationProperties("spring.shardingsphere.datasource.ds-storage")
    public DataSource dsStorage() {
        return new HikariDataSource();
    }

    @Bean("dsOrder")
    @ConfigurationProperties("spring.shardingsphere.datasource.ds-order")
    public DataSource dsOrder() {
        return new HikariDataSource();
    }

    @Bean("dsAccount")
    @ConfigurationProperties("spring.shardingsphere.datasource.ds-account")
    public DataSource dsAccount() {
        return new HikariDataSource();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(@Qualifier("dsStorage") DataSource dsStorage,
                                        @Qualifier("dsOrder") DataSource dsOrder,
                                        @Qualifier("dsAccount") DataSource dsAccount) {
        Map<Object, Object> targetDataSources = new HashMap<>(3);
        targetDataSources.put(DataSourceNames.DS_STORAGE, dsStorage);
        targetDataSources.put(DataSourceNames.DS_ORDER, dsOrder);
        targetDataSources.put(DataSourceNames.DS_ACCOUNT, dsAccount);
        return new DynamicDataSource(dsOrder, targetDataSources);
    }
}
